<template>
  <div class="admin-container">

    <!-- 主内容区域 -->
    <div class="main-content">

      <!-- 右侧内容区域 -->
      <main class="content">
        <!-- 求职申请审核内容 -->
        <div class="job-application-audit">
          <div class="page-header">
            <h2>求职申请审核</h2>
          </div>

          <!-- 筛选条件 -->
          <el-card class="filter-card">
            <el-form :inline="true" :model="filterForm" size="small">
              <el-form-item label="职位名称">
                <el-input v-model="filterForm.jobTitle" placeholder="请输入职位名称"></el-input>
              </el-form-item>
              <el-form-item label="申请人">
                <el-input v-model="filterForm.applicant" placeholder="请输入申请人"></el-input>
              </el-form-item>
              <el-form-item label="申请状态">
                <el-select v-model="filterForm.status" placeholder="全部状态">
                  <!-- 显式定义选项，确保label和value对应 -->
                  <el-option label="待审核" value="0"></el-option>
                  <el-option label="已通过" value="1"></el-option>
                  <el-option label="已拒绝" value="2"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="fetchApplications">查询</el-button>
                <el-button @click="resetFilter">重置</el-button>
              </el-form-item>
            </el-form>
          </el-card>

          <!-- 申请列表 -->
          <el-card class="application-list">
            <el-table :data="applications.list" border stripe v-loading="loading" element-loading-text="加载中...">
              <el-table-column prop="application_id" label="申请ID" width="100"></el-table-column>
              <el-table-column prop="job_title" label="职位名称"></el-table-column>
              <el-table-column prop="company" label="公司"></el-table-column>
              <el-table-column prop="applicant" label="申请人" width="200"></el-table-column>
              <el-table-column prop="status" label="状态" width="120">
                <template #default="scope">
                  <el-tag :type="scope.row.status === 0 ? 'warning' : scope.row.status === 1 ? 'success' : 'danger'">
                    {{ scope.row.status === 0 ? '待审核' : scope.row.status === 1 ? '已通过' : '已拒绝' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="applied_at" label="申请时间" width="180"></el-table-column>
              <el-table-column label="操作" width="300">
                <template #default="scope">
                  <el-button size="small" type="text" @click="viewResume(scope.row.resume_id)">
                    查看简历
                  </el-button>
                  <el-button size="small" type="success" @click="handleReview(scope.row, 1)"
                    v-if="scope.row.status === 0">
                    通过
                  </el-button>
                  <el-button size="small" type="danger" @click="handleReview(scope.row, 2)"
                    v-if="scope.row.status === 0">
                    拒绝
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页 -->
            <el-pagination v-if="applications.pagination.total > 0" :current-page="applications.pagination.page"
              :page-size="applications.pagination.pageSize" :total="applications.pagination.total"
              :page-sizes="[10, 20, 50]" layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange" @current-change="handlePageChange"></el-pagination>
          </el-card>

          <!-- 审核备注弹窗 -->
          <el-dialog v-model="reviewDialogVisible" title="审核操作" :before-close="handleDialogClose">
            <el-form :model="reviewForm" size="small">
              <el-form-item label="审核备注" prop="note">
                <el-input v-model="reviewForm.note" type="textarea" rows="4" placeholder="请输入审核备注（选填）"
                  maxlength="500"></el-input>
              </el-form-item>
            </el-form>
            <template #footer>
              <el-button @click="reviewDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="confirmReview">确认</el-button>
            </template>
          </el-dialog>

          <!-- 简历图片查看弹窗 -->
          <el-dialog v-model="resumeDialogVisible" title="简历图片" width="80%"
            :before-close="() => resumeDialogVisible = false">
            <div class="resume-image-container">
              <img :src="resumeImageUrl" alt="简历图片" class="resume-image" v-if="resumeImageUrl">
              <div v-else class="resume-loading">加载中...</div>
            </div>
          </el-dialog>
        </div>
      </main>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import { useAdminStore } from '@/stores/admin'
import * as jobApi from '@/api/job'
import resumeApi from '@/api/resume'
import * as applicationApi from '@/api/jobApplication'

const router = useRouter()
const route = useRoute()
const { proxy } = getCurrentInstance()
const adminStore = useAdminStore()



// 状态管理
const loading = ref(false)
const applications = ref({
  list: [],
  pagination: {
    page: 1,
    pageSize: 10,
    total: 0,
    totalPages: 0
  }
})

// 简历图片弹窗相关
const resumeDialogVisible = ref(false)
const resumeImageUrl = ref('')

// 审核弹窗
const reviewDialogVisible = ref(false)
const reviewForm = reactive({
  note: '',
  currentApplication: null,
  action: 1 // 1-通过 2-拒绝
})

// 页面加载时初始化
onMounted(() => {
  // 检查管理员登录状态
  if (!adminStore.isAdminLoggedIn()) {
    console.log('管理员未登录，跳转到登录页')
    router.push('/admin/login')
    return
  }
  fetchApplications()
})

// 侧边栏相关方法
const handleSidebarSelect = (index) => {
  console.log('导航到:', index)
}

const handleQuickAction = (actionId) => {
  ElMessage.info(`执行快捷操作: ${actionId}`)
}

const statusOptions = ref([
  { label: '待审核', value: '0' },
  { label: '已通过', value: '1' },
  { label: '已拒绝', value: '2' }
])

const filterForm = reactive({
  jobTitle: '',
  applicant: '',
  status: ''  // 初始为空，选中后存储 '0'/'1'/'2'，下拉框会自动显示对应的 label
})

// 获取申请列表
const fetchApplications = async () => {
  try {
    loading.value = true
    const params = {
      page: applications.value.pagination.page,
      pageSize: applications.value.pagination.pageSize,
      status: filterForm.status,  // 直接传实际值（'0'/'1'/'2' 或空）
      jobTitle: filterForm.jobTitle,
      applicant: filterForm.applicant
    }
    const res = await applicationApi.getAdminApplications(params)
    if (res.code === 0) {
      applications.value = res.data
    } else {
      ElMessage.error(res.msg || '获取申请列表失败')
    }
  } catch (error) {
    ElMessage.error('获取申请列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 分页处理
const handleSizeChange = (pageSize) => {
  applications.value.pagination.pageSize = pageSize
  applications.value.pagination.page = 1
  fetchApplications()
}

const handlePageChange = (page) => {
  applications.value.pagination.page = page
  fetchApplications()
}

// 重置筛选条件
const resetFilter = () => {
  filterForm.jobTitle = ''
  filterForm.applicant = ''
  filterForm.status = ''  // 重置为空，显示"全部状态"
  fetchApplications()
}

// 查看简历
const viewResume = async (resumeId) => {
  console.log('传递的resume_id:', resumeId, '类型:', typeof resumeId);

  try {
    if (!resumeId || isNaN(Number(resumeId))) {
      ElMessage.error('简历ID无效（必须是数字）');
      return;
    }

    resumeImageUrl.value = '';
    resumeDialogVisible.value = true;

    const res = await resumeApi.getById(Number(resumeId));
    if (res.code === 0) {
      resumeImageUrl.value = res.data.file_url;
    } else {
      ElMessage.error(res.msg || '获取简历失败');
      resumeDialogVisible.value = false;
    }
  } catch (error) {
    ElMessage.error('获取简历失败');
    console.error(error);
    resumeDialogVisible.value = false;
  }
};

// 处理审核操作
const handleReview = (application, action) => {
  reviewForm.currentApplication = application
  reviewForm.action = action
  reviewForm.note = ''
  reviewDialogVisible.value = true
}

// 确认审核
const confirmReview = async () => {
  if (!reviewForm.currentApplication) return;

  try {
    const { application_id, status: currentStatus } = reviewForm.currentApplication;
    if (currentStatus !== 0) {
      ElMessage.warning('该申请已被处理，无需重复审核');
      reviewDialogVisible.value = false;
      return;
    }

    const res = await applicationApi.review(application_id, {
      status: reviewForm.action,
      note: reviewForm.note
    });

    if (res.code === 0) {
      ElMessage.success(reviewForm.action === 1 ? '审核通过' : '已拒绝');
      const targetIndex = applications.value.list.findIndex(
        item => item.application_id === application_id
      );
      if (targetIndex > -1) {
        applications.value.list[targetIndex].status = reviewForm.action;
      }
      reviewDialogVisible.value = false;
    } else {
      ElMessage.error(res.msg || '审核操作失败');
    }
  } catch (error) {
    ElMessage.error('审核操作失败');
    console.error(error);
  }
};

// 关闭弹窗
const handleDialogClose = () => {
  reviewDialogVisible.value = false
}

// 管理员操作处理
const handleAdminCommand = (command) => {
  switch (command) {
    case 'profile':
      ElMessage.info('跳转到管理员资料')
      break
    case 'settings':
      ElMessage.info('跳转到系统设置')
      break
    case 'back':
      router.push('/')
      break
    case 'logout':
      handleLogout()
      break
  }
}

// 退出登录处理
const handleLogout = async () => {
  try {
    await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await adminStore.adminLogout()
    ElMessage.success('已退出登录')
    router.push('/admin/login')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('退出失败:', error)
      adminStore.clearAdminData()
      router.push('/admin/login')
    }
  }
}
</script>

<style scoped>
/* 基础布局样式 */
.admin-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

/* 头部样式 */
.header {
  background: #ffffff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 1000;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  height: 64px;
}

.logo-section {
  display: flex;
  align-items: center;
}

.logo {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: bold;
  color: #409EFF;
}

.logo-text {
  font-size: 18px;
  font-weight: 600;
}

.header-right {
  display: flex;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 6px;
  transition: background-color 0.3s;
}

.user-info:hover {
  background-color: #f5f7fa;
}

.user-email {
  font-size: 14px;
  color: #606266;
}

/* 侧边栏样式 */
.sidebar {
  width: 280px;
  background: #ffffff;
  box-shadow: 2px 0 8px 0 rgba(29, 35, 41, 0.05);
  overflow-y: auto;
}

.sidebar-content {
  padding: 20px 0;
}

.sidebar-title {
  font-size: 14px;
  color: #8c8c8c;
  margin: 0 20px 12px;
  font-weight: 500;
}

.sidebar-menu {
  border-right: none;
}

.sidebar-menu .el-menu-item {
  height: 48px;
  line-height: 48px;
  margin: 0 12px;
  border-radius: 6px;
}

.sidebar-menu .el-menu-item.is-active {
  background-color: #ecf5ff;
}

.badge {
  margin-left: auto;
}

/* 快捷操作 */
.action-list {
  padding: 0 20px;
}

.action-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.action-item:hover {
  background-color: #f5f7fa;
}

.action-text {
  font-size: 14px;
  color: #303133;
}

/* 系统状态 */
.status-list {
  padding: 0 20px;
}

.status-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.status-item:last-child {
  border-bottom: none;
}

.status-label {
  font-size: 14px;
  color: #606266;
}

/* 内容区域样式 */
.main-content {
  flex: 1;
  display: flex;
  overflow-y: hidden;
}

.content {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
}

/* 求职申请审核页面样式 */
.job-application-audit {
  width: 100%;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.application-list {
  min-height: 500px;
}

::v-deep .el-table__empty-text {
  height: 300px;
}

.resume-image-container {
  text-align: center;
  padding: 20px 0;
}

.resume-image {
  max-width: 100%;
  max-height: 70vh;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.resume-loading {
  color: #666;
  padding: 50px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-content {
    padding: 0 16px;
  }

  .sidebar {
    width: 240px;
  }

  .job-application-audit {
    padding: 10px;
  }

  .content {
    padding: 16px;
  }
}

::v-deep .el-select {
  width: 180px;
  /* 确保宽度足够显示文字 */
}

::v-deep .el-select__input {
  color: #303133 !important;
  /* 文字颜色（与主题匹配） */
  text-indent: 0 !important;
  /* 取消缩进，避免文字偏移 */
  opacity: 1 !important;
  /* 确保不透明 */
}

/* 选中后下拉框的文字样式 */
::v-deep .el-select__selected-label {
  color: #303133 !important;
}
</style>